package com.attendancesystem.controller;


import com.attendancesystem.model.Unit;
import com.attendancesystem.service.UnitService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import javax.servlet.annotation.WebServlet;
import java.io.IOException;
@WebServlet(name = "UpdateUnitController", value = "/UpdateUnitController")
public class UpdateUnitController extends HttpServlet {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        UnitService unitService = new UnitService();
        JsonNode rootNode = objectMapper.readTree(req.getReader());
        Unit unit = new Unit();
        String unitId = req.getParameter("unitId");
        String unitName = rootNode.get("unitName").asText();
        String unitDescription = rootNode.get("unitDesc").asText();
        String courseId = rootNode.get("courseId").asText();
        String unitDuration = rootNode.get("unitDuration").asText();
        System.out.println("unitId:"+unitId);
        System.out.println("unitName:"+unitName);
        System.out.println("unitDescription:"+unitDescription);
        System.out.println("courseId:"+courseId);
        System.out.println("unitDuration:"+unitDuration);
        unit.setUnitId(Integer.parseInt(unitId));
        unit.setUnitName(unitName);
        unit.setUnitDescription(unitDescription);
        unit.setCourseId(Integer.parseInt(courseId));
        unit.setUnitDuration(Integer.parseInt(unitDuration));
        if (unitService.updateUnit(unit)){
            resp.getWriter().print("{\"status\":\"success\"}");
        }else {
            resp.getWriter().print("{\"status\":\"failed\"}");
        }

    }

}
